'use strict';
const {
  Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
  class Category extends Model {
    /**
     * Helper method for defining associations.
     * This method is not a part of Sequelize lifecycle.
     * The `models/index` file will call this method automatically.
     */
    static associate(models) {
      // define association here
    }
  }
  Category.init({
    name:{
      type: DataTypes.STRING,// 字符串类型
      allowNull: false,//不允许为空
        // 自定义校验器
      validate: {
        // 缺少属性提示
        notNull: {
          msg: "缺少name属性"
        },
        // 传值为空提示
        notEmpty: {
          msg: '名称不能为空'
        },
        // 长度校验提示
        len:{
          args:[2,45],
          msg:'名称长度需要在2~45个字符之间'
        },
        async isUnique(value) {
          const count = await Category.count({
            where: {
              name: value
            }
          })
          if (count > 0) {
            throw new Error('名称已经存在')
          }
        }
      },
    },
    rank: {
      type: DataTypes.INTEGER,
      allowNull: false,
      validate: {
        notNull: {
          msg: "缺少rank属性"
        },
        notEmpty: {
          msg: '排序不能为空'
        },
        isInt: {
          msg: '排序必须是整数'
        },
        isPositive(value) {
         if (value < 0) {
          throw new Error('排序必须是正整数')
         }
        }
      }
    }
  }, {
    sequelize,
    modelName: 'Category',
  });
  return Category;
};